package com.wdullaer.materialdatetimepicker;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.render.Canvas;
import ohos.agp.utils.Rect;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;

/**
 * Text that renders it's contents vertically. (Just using rotate doesn't work because onMeasure
 * happens before the Component is rotated causing incorrect Component boundaries)
 * Created by wdullaer on 28/03/16.
 */
public class VerticalTextView extends Text {
    final boolean topDown;

    static final int VERTICAL_ALIGNMENT_MASK = TextAlignment.TOP | TextAlignment.BOTTOM | TextAlignment.VERTICAL_CENTER;
    static final int HORIZONTAL_ALIGNMENT_MASK = TextAlignment.LEFT | TextAlignment.RIGHT | TextAlignment.HORIZONTAL_CENTER;

    public static boolean isVertical(int gravity) {
        return gravity > 0 && (gravity & VERTICAL_ALIGNMENT_MASK) != 0;
    }

    public VerticalTextView(Context context, AttrSet attrs) {
        super(context, attrs);
        final int alignment = getTextAlignment();
        if (isVertical(alignment) && (alignment & VERTICAL_ALIGNMENT_MASK) == TextAlignment.BOTTOM) {
            setTextAlignment((alignment & HORIZONTAL_ALIGNMENT_MASK) | TextAlignment.TOP);
            topDown = false;
        } else {
            topDown = true;
        }
        addDrawTask(drawTask);
    }

    DrawTask drawTask = new DrawTask() {
        @Override
        public void onDraw(Component component, Canvas canvas) {
            canvas.save();

            Rect rect = getComponentPosition();
            if (topDown) {
                canvas.translate(getWidth(), 0);
                canvas.rotate(90, rect.getCenterX(), rect.getCenterY());
            } else {
                canvas.translate(0, getHeight());
                canvas.rotate(-90, rect.getCenterX(), rect.getCenterY());
            }
            canvas.restore();
        }
    };
}
